<script setup>
import { list, deleteMany } from '@/api/image'
import { onMounted, ref } from 'vue'
import { Delete, Plus, Picture } from '@element-plus/icons-vue'
import { API_TOKEN_STORAGE_KEY,imgUploadApi,getImgUrl } from '@/api/request'
import { ElMessage } from 'element-plus'

const props = defineProps({
  imageList: {
    default: [],
    type: Array
  },
  showList: {
    default: true,
    type: Boolean
  },
  max: {
    default: 5,
    type: Number
  },
  compressImage: {
    default: false,
    type: Boolean
  }
})
const emits = defineEmits(['change'])

const imageLibrary = ref([])
const loading = ref(false)
const currentPage = ref(1)
const totalRow = ref(0)
const pageSize = ref(9)

const showModel = ref(false)

async function loadList() {
  try {
    loading.value = true
    const res = await list({
      page_size: pageSize.value,
      page: currentPage.value
    })
    imageLibrary.value = res.data
    totalRow.value = res.total
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadList()
  
})
function onPageChanged(p) {
  currentPage.value = p
  loadList()
}
function showImgModel() {
  showModel.value = true
}
function handleDelete(index) {
  const toDelete = props.imageList[index]
  props.imageList.splice(index, 1)
  emits('change', props.imageList, {remove: toDelete})
}
async function handleImageDelete(id) {
  await deleteMany({ids: [id]})
  ElMessage.success('删除成功')
  loadList()
}
// function getImgUrl(url) {
//   return import.meta.env.VITE_APP_IMG_BASE_URL + url
// }
function addImageId(url) {
  if (props.max > 0 && props.imageList.length + 1 > props.max) {
    if (!props.showList.value) {
      props.imageList.shift()
    }else{
      return
    }
  }
  props.imageList.push(url)
  emits('change', props.imageList, {add: url})
  showModel.value = false
}
const uploading = ref(false)
// const uploadAction = imgUploadApi
const uploadHeader = {
  Authorization: localStorage.getItem(API_TOKEN_STORAGE_KEY)
}
function beforeUpload(e) {
  console.log('beforeUpload')
  uploading.value = true
}
function onUploadSuccess(res) {
  console.log(res)
  if (res.code == 1) {
    ElMessage.success('上传成功')
    currentPage.value = 1
    loadList()
  }else{
    ElMessage.error(res.msg?res.msg:'上传失败')
  }
  uploading.value = false
  
}
function onUploadError(e) {
  console.log(e)
  ElMessage.error(`上传失败${e}`)
  uploading.value = false
}
</script>

<template>
  <div class="component">
    <div class="image-list" v-if="props.showList">
      <div v-for="(item,i) in props.imageList" :key="item" class="img-item">
        <img :src="getImgUrl(item)" />
        <div class="img-delete-btn" @click="handleDelete(i)">
          <el-icon><delete /></el-icon>
        </div>
      </div>
    </div>
    <div v-if="props.showList && ((max > 0 && props.imageList.length < max) || max <= 0)" class="img-item" @click="showImgModel">
      <div class="add-img-item">
        <div class="add-icon-holder">
          <el-icon class="add-icon"><plus /></el-icon>
        </div>
        <div v-if="max>0">{{props.imageList.length+1}}/{{max}}</div>
      </div>
    </div>
    <el-button v-if="!props.showList" @click="showImgModel"><el-icon><Picture /></el-icon>插入图片</el-button>
    <!-- 这里有warning 暂时不知道怎么处理 -->
    <el-dialog v-model="showModel" title="图片" :width="600" >
      <div v-loading="loading || uploading">
        <div  class="img-list">
          <div v-for="item in imageLibrary" :key="item.id" class="img-item">
            <img :src="getImgUrl(item.url)" @click="addImageId(item.url)" />
            <el-popconfirm
              title="从服务器上删除?"
              @confirm="handleImageDelete(item.id)"
            >
              <template #reference>
                <div class="img-delete-btn">
                  <el-icon><delete /></el-icon>
                </div>
              </template>
              
            </el-popconfirm>
          </div>
          <!-- <a-spin :spinning="uploading"> -->
          <el-upload
            name="file"
            :action="imgUploadApi"
            :headers="uploadHeader"
            :on-success="onUploadSuccess"
            :on-error="onUploadError"
            :showFileList="false"
            :beforeUpload="beforeUpload"
            drag
          >
          <!-- accept=".png,.jpeg,.jpg" -->
            <div class="img-item">
              <div class="add-img-item">
                <div class="add-icon-holder">
                  <el-icon class="add-icon"><plus /></el-icon>
                </div>
                <div @click.stop="">
                  <!-- <a-checkbox v-model="isCompressImage">压缩上传</a-checkbox> -->
                </div>
              </div>
            </div>
          </el-upload>
        </div>
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalRow"
          @current-change="onPageChanged"
        />
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.img-list {
  display: flex;
  flex-wrap: wrap;
}
.img-item {
  width: 100px;
  height: 100px;
  /* float: left; */
  border: 1px solid #fff;
  margin: 2px;
  padding: 2px;
  cursor: pointer;
  position: relative;
}
.img-item:hover {
  border-color: #3c91f7;
}
.img-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.add-img-item {
  width: 100%;
  height: 100%;
  background: #eee;
  text-align: center;
  display: flex;
  flex-direction: column;
}
.add-icon-holder {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.add-icon {
  font-size: 24px;
}
.img-delete-btn {
  position: absolute;
  top: 0;
  left: 0;
  color: #fff;
  background: #f50;
  width: 30px;
  height: 30px;
  text-align: center;
  line-height: 30px;
}

</style>
<style>
.el-upload-dragger {
  width: auto;
  height: auto;
}
</style>